/*
 * UploadFile.java
 *
 */

package edu.byu.isys413.actions;

import edu.byu.isys413.group1E.data.*;
import edu.byu.isys413.group1E.handlers.FileHandler;
import java.util.*;
import javax.servlet.http.*;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.FileItem;

 /** This class responds to a call from the gui to process a request to upload 
  *additional files to the database.
  *
  *@author Travis Kulbeth
  */
public class UploadFile implements edu.byu.isys413.web.Action {
    
    /** Creates a new instance of NumberGame */
    public UploadFile() {
    }
  
    /**
     * Process method uploads up to 3 files to the database, attributed to the member who owns it.  If
     * the member does not have sufficient storage space for the additional files, this method requests
     * that the user purchase more space.  When the user completes that process, he or she is returned to the 
     * storage space and can re-upload the files.  Otherwise, the files are uploaded and the user is returned to 
     * the page containing the stored files to view their backed up data.
     * @param request contains the HttpServletRequest data
     * @param response contains the HttpServletResponse data
     * @return String the name of the jsp to call
     * @throws java.lang.Exception to catch any errors and forward them to the ui level
     */
    public String process(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        // parse the request using the Jakarta file upload library
        // convert the requestParams into a map.  this assumes that each form field on
        // the page has a unique name.  if two fields have the same name, the second
        // one will blast the first one
        ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());
        List paramList = servletFileUpload.parseRequest(request);
        Map params = new TreeMap();

        
        for (int i = 0; i < paramList.size(); i++) {
            FileItem item = (FileItem)paramList.get(i);
            params.put(item.getFieldName(), item);
        }//for
            
        // get a file parameters from the request
        FileItem item1 = (FileItem)params.get("file1");
        FileItem item2 = (FileItem)params.get("file2");
        FileItem item3 = (FileItem)params.get("file3");
        
        double groupSize = 0;
        
        //check the sizes
        if(!item1.getName().equals("")){
            groupSize += item1.getSize();
        }
        if(!item2.getName().equals("")){
            groupSize += item2.getSize();
        }
        if(!item3.getName().equals("")){
            groupSize += item3.getSize();
        }

        //check the size against the member's available backup space
        CustomerBO cust = (CustomerBO)session.getAttribute("customer");
        MembershipBO memb = cust.getCustMembership();
        ArrayList<BackupDataBO> currentBackups = BackupDataDAO.getInstance().readByMember(memb.getMembershipID());
        //find the used backup space and calculate the remaining space
        double usedSpace = 0;
        for(int x=0;x<currentBackups.size();x++){
            usedSpace += currentBackups.get(x).getFileSize();
        }
        double availSpace = (memb.getBuSize() * 1000000000) - usedSpace;
//        double availSpace = memb.getBuSize() - usedSpace;        
        //if the size is too big for the space, show message and page to add more space
        if(groupSize > availSpace){
            String message = new String("You do not have sufficient space in your backup storeage. " +
                    "<br /><ul><li>Total space: " + 
                    memb.getBuSize() + " GB</li><li>Currently used: " + (usedSpace/1000000000) + " GB</li><li>Currently Available: " + 
                    (availSpace/1000000000) + " GB</li><li>Needed: " + (groupSize/1000000000) + " GB</li></ul>");
            request.setAttribute("message", message);
            return "orderspace.jsp";
        }
        
        //now send the files to be saved
        if(!item1.getName().equals("")){
            FileHandler.getInstance().saveFileToDB(item1,memb.getMembershipID(), "permanent");
        }
        if(!item2.getName().equals("")){
            FileHandler.getInstance().saveFileToDB(item2,memb.getMembershipID(), "permanent");
        }
        if(!item3.getName().equals("")){
            FileHandler.getInstance().saveFileToDB(item3,memb.getMembershipID(), "permanent");
        }
        
        return "edu.byu.isys413.actions.loadExistingStorage.action";
    }//process
}